import asyncio
import threading
import time
from io import BytesIO

import edge_tts
import pygame
def speech( message: str, voice: str):
    """
       使用edgetts库将消息转换为语音并播放。
       使用pygame播放音频，在新线程中执行，避免阻塞主线程。
    """

    def _speech_task():
        # 初始化pygame mixer
        pygame.mixer.init(frequency=24000, channels=1)
        try:
            # 定义异步任务
            async def _async_speech():
                audio_buffer = BytesIO()
                # 创建edge-tts流

                communicate = edge_tts.Communicate(message, voice,rate='+25%')
                # 异步收集音频数据
                async for chunk in communicate.stream():
                    if chunk["type"] == "audio":
                        audio_buffer.write(chunk["data"])
                return audio_buffer

            # 在新线程中运行异步任务
            audio_buffer = asyncio.run(_async_speech())
            audio_buffer.seek(0)

            # 加载并播放音频
            pygame.mixer.music.load(audio_buffer)
            pygame.mixer.music.play()

            # 等待播放完成
            while pygame.mixer.music.get_busy():
                time.sleep(0.1)

        except Exception as e:
            print(f"语音播放出错: {e}")
        finally:
            # 清理资源
            pygame.mixer.music.stop()
            pygame.mixer.quit()
            if 'audio_buffer' in locals():
                audio_buffer.close()

    # 创建并启动新线程
    thread = threading.Thread(target=_speech_task)
    thread.daemon = True  # 设置为守护线程，主线程退出时自动结束
    thread.start()
    return thread


if __name__ == "__main__":
    speech("使用AudioSegment.from_mp3方法将 MP3 数据转换为音频对象。",voice= "zh-CN-XiaoxiaoNeural")
    input("按任意键退出...")